package com.bc.web.controller.merch;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bc.common.CommonEnum.OrderStatus;
import com.bc.web.config.SystemConfig;
import com.bc.web.model.Dictionary;
import com.bc.web.model.MerchUser;
import com.bc.web.model.Org;
import com.bc.web.model.TradeOrder;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSIDWorker;
import com.fs.common.util.FSJson;
import com.fs.common.util.FSLog;
import com.fs.common.util.FSMD5;
import com.fs.common.util.FSThreadPoolExecutor;
import com.jfinal.plugin.activerecord.Page;

public class TradeOrderController extends FSController {

	public void search() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute("merchUser");
		List<Dictionary> payTypeList = Dictionary.dao.selectPayType();
		Page<TradeOrder> pageResult = TradeOrder.dao.searchForMerch(super.getSearchCondition(), merchUser.getMerchCode());
		for (TradeOrder to : pageResult.getList()) {
			for (Dictionary payType : payTypeList) {
				if (to.getPayType().equals(payType.getCode())) {
					to.put("payTypeName", payType.getName());
					break;
				}
			}
		}
		setAttr("payTypeList", payTypeList);
		setPageResultToRequest("items", pageResult);
		render("order/orderList.html");
	}

	public void view() {
		TradeOrder tradeOrder = TradeOrder.dao.findById(getPara("id"));
		// 支付类别
		Dictionary dictionary = Dictionary.dao.selectByKey(tradeOrder.getPayType());
		tradeOrder.put("payTypeName", dictionary.getName());
		if(tradeOrder.getTotalFee() == null) {
			tradeOrder.put("totalFee", tradeOrder.getAmount());
		}
		setAttr("order", tradeOrder);
		
		List<TradeOrder> ogoRefOrderList = TradeOrder.dao.find(
				"select * from trade_order where originalOrderNo=? AND payType=? AND orderStatus is not NULL", tradeOrder.getOrderNo(),
				"wxgjpay_refund");
		if (ogoRefOrderList == null || ogoRefOrderList.isEmpty()) {
			setAttr("isRef", 0);
		} else {
			{
				setAttr("isRef", ogoRefOrderList.size());
				setAttr("ReforderList", ogoRefOrderList);
			}
		}
		
		render("order/orderView.html");
	}

	/**
	 * 推送
	 */
	public void push(){
		String[] ids = getParaValues("ids");
		FSThreadPoolExecutor.execute(new Runnable() {
			@Override
			public void run() {
				for (String id : ids) {
					try {
						String result = FSHttp.postString(SystemConfig.config.get("trade_system_url") + "/notify/adminPush", id);
						FSLog.web.info("商户补发通知结果 <-" + result);
					} catch (Exception e) {
						FSLog.web.error("商户补发通知异常",e);
					}
				}
			}
		});
		renderSuccess("补发通知成功",false);
	}
	
	

	public void refurd() {
		String yuanyin = getPara("yuanyin");
		String orgCode = getPara("orgCode");
		String merchCode = getPara("merchCode");
		String orderNo = getPara("orderNo");
		String channelOrderNo = getPara("channelOrderNo");
		String refund_fee = getPara("refund_fee");
		
		String amount = null;
		if (refund_fee.contains(".")) {
			String[] names = refund_fee.split("\\.");
			amount = refund_fee.replace(".", "");
			if (names[1].length() == 1) {
				int amt = Integer.parseInt(amount) * 10;
				amount = amt + "";
			} else if (names[1].length() == 2) {
				int amt = Integer.parseInt(amount) * 1;
				amount = amt + "";
			}
		} else {
			amount = refund_fee;
			int amt = Integer.parseInt(amount) * 100;
			amount = amt + "";
		}
		
		
		
		FSLog.api.info("退款原因 ------ > " + (yuanyin) + "," + channelOrderNo);
		List<TradeOrder> trList = TradeOrder.dao.find(
				"select * from trade_order where orgCode=? AND merchCode=? AND channelOrderNo=? AND orderNo=?", orgCode,
				merchCode, channelOrderNo, orderNo);
		if (trList == null || trList.isEmpty()) {
			renderHtml("找不到此订单");
			return;
		}
		if (trList.size() > 1) {
			renderHtml("此订单重复");
			return;
		}
		TradeOrder tradeOrder = trList.get(0);
		if (!"TS".equals(tradeOrder.getOrderStatus())) {
			renderHtml("此订单不满足退款条件:没有支付成功!!!");
			return;
		}
		List<TradeOrder> ogoRefOrderList = TradeOrder.dao.find(
				"select * from trade_order where originalOrderNo=? AND payType=?", tradeOrder.getOrderNo(),
				"wxgjpay_refund");
		if (ogoRefOrderList == null || ogoRefOrderList.isEmpty()) {

		}else {
			int allRefundFee = 0;
			for(int i = 0; i < ogoRefOrderList.size(); i++) {
				String status = ogoRefOrderList.get(i).getOrderStatus();
				if(OrderStatus.DoRefund.getValue().equals(status) || OrderStatus.Refund.getValue().equals(status)) {
					allRefundFee += ogoRefOrderList.get(i).getAmount(); //已经退款的总金额
				}else if(OrderStatus.Fail.getValue().equals(status)){
					renderHtml("此订单存在退款失败的订单数据,请先处理退款失败的订单:" + ogoRefOrderList.get(i).getOrderNo() + 
							",失败原因:" + ogoRefOrderList.get(i).getRespMsg());
					return;
				}
			}
			if(tradeOrder.getTotalFee() - Integer.parseInt(amount) + allRefundFee < 0) {
				renderHtml("退款总金额已经超出原交易总金额了...");
				return;
			}
		}
		
		if (!"wxgipay".equals(tradeOrder.getChannelCode())) {
			renderHtml("此订单渠道编号:" + tradeOrder.getChannelCode() + ",不支持退款");
			return;
		}

		String isok = "";
		try {
			FSLog.api.info("开始............退款...............");
			isok = reftoWeixin(tradeOrder, yuanyin, Integer.parseInt(amount));
		} catch (Exception e) {
			// TODO: handle exception
		}
		if ("ok".equals(isok)) {
			renderHtml("退款申请成功");
		} else {
			renderHtml(isok);
		}
	}
	
	private String reftoWeixin(TradeOrder tradeOrder, String yuanyin, int refAmt) throws Exception {
		
		Map<String, String> map = new HashMap<>();
		map.put("version", "V1.0");
		map.put("orgCode", tradeOrder.getOrgCode());
		map.put("merchCode", tradeOrder.getMerchCode());
		map.put("refundOrderNo", tradeOrder.getMerchOrderNo());
		map.put("merchOrderNo", "RF" + FSIDWorker.getNext());
		map.put("amount", refAmt+"");//本次退款金额
		map.put("remark", yuanyin);
		map.put("payType", "wxgjpay_refund");
		Org org = Org.dao.selectByOrgCode(tradeOrder.getOrgCode());
		String tradeSystemUrl = SystemConfig.config.get("trade_system_url") + "/route";
		map.put("sign", FSMD5.sortSign(map, org.getSafeKey()));
		String sendJson = FSJson.toString(map);
		FSLog.api.info("00.web上送退款数据:" + sendJson);
		String res = FSHttp.postJson(tradeSystemUrl, sendJson);
		FSLog.api.info("01.web返回退款数据:" + res);
		Map<String, String> resmap = FSJson.toMap(res);
		
		if (resmap.get("respCode").equals("00")) {
			String origiOrderRespCode = resmap.get("originalRespCode");
			if (origiOrderRespCode.equals("00")) {
				return ("退款申请结果:订单退款申请成功");
			} else {
				return ("退款申请结果:订单[" + resmap.get("originalRespMsg") + "]");
			}
		} else {
			return ("退款申请结果:交易系统返回" + resmap.get("respMsg"));
		}
	}
	
	public void queryRefurd() {
		String orgCode = getPara("orgCode");
		String merchCode = getPara("merchCode");
		String orderNo = getPara("orderNo");
		
		List<TradeOrder> trList = TradeOrder.dao.find("select * from trade_order where orgCode=? AND merchCode=? AND orderNo=? AND payType=?", 
				orgCode, merchCode, orderNo, "wxgjpay_refund");
		if(trList==null || trList.isEmpty() || trList.size() > 1) {
			renderHtml("此退款订单信息错误: trList==null || trList.isEmpty() || trList.size() > 1");
			return;
		}
		TradeOrder refOrder = trList.get(0);
		List<TradeOrder> oldTrList = TradeOrder.dao.find("select * from trade_order where orgCode=? AND merchCode=? AND orderNo=?", 
				orgCode, merchCode, refOrder.getOriginalOrderNo());
		
		if(oldTrList==null || oldTrList.isEmpty() || oldTrList.size() > 1) {
			renderHtml("此退款的原订单信息错误: oldTrList==null || oldTrList.isEmpty() || oldTrList.size() > 1");
			return;
		}
		TradeOrder oldOrder = oldTrList.get(0);
		Map<String, String> map = new HashMap<>();
		map.put("version", "V1.0");
		map.put("orgCode", oldOrder.getOrgCode());
		map.put("merchCode", oldOrder.getMerchCode());
		map.put("refundOrderNo", oldOrder.getMerchOrderNo());
		map.put("payType", "wxgjpay_refund_query");
		Org org = Org.dao.selectByOrgCode(oldOrder.getOrgCode());
		String tradeSystemUrl = SystemConfig.config.get("trade_system_url") + "/route";
		map.put("sign", FSMD5.sortSign(map, org.getSafeKey()));
		String sendJson = FSJson.toString(map);
		
		try {
			FSLog.api.info("00.web退款查询 上送退款数据:" + sendJson);
			String res = FSHttp.postJson(tradeSystemUrl, sendJson);
			FSLog.api.info("01.web退款查询 返回退款数据:" + res);
			Map<String, String> resmap = FSJson.toMap(res);
			
			renderHtml(resmap.toString());
		}catch (Exception e) {
			// TODO: handle exception
			renderHtml(e.toString());
		}
		
	}
	

	
	
	
}
